package com.unlcn.ils.wms.web.controller.sys;

import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import com.unlcn.ils.wms.backend.service.sys.CardService;
import com.unlcn.ils.wms.backend.util.DateUtils;
import com.unlcn.ils.wms.base.model.stock.WmsBorrowCar;
import com.unlcn.ils.wms.base.model.sys.SysUser;
import com.unlcn.ils.wms.base.model.sys.WmsCard;
import com.unlcn.ils.wms.web.vo.borrow.WmsBorrowCarVo;
import com.unlcn.ils.wms.web.vo.sys.WmsCardVo;
import jodd.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lenovo on 2017/11/2.
 */
@Controller
@RequestMapping("/card")
@ResponseBody
public class CardController {

    private Logger LOGGER = LoggerFactory.getLogger(CardController.class);

    @Autowired
    private CardService cardService;

    /**
     * 门禁卡列表
     *
     * @param wmsCardVo
     * @return
     */
    @RequestMapping(value = "/cardLine", method = RequestMethod.POST)
    public ResultDTO<Object> cardLine(@RequestBody WmsCardVo wmsCardVo) {
        LOGGER.info("CardController.cardLine param: {}" + wmsCardVo.toString());
        ResultDTO resultDTO = null;

        try {
            Map<String, Object> paramsMap = new HashMap<String, Object>();
            paramsMap.put("limitStart", wmsCardVo.getStartIndex());
            paramsMap.put("limitEnd", wmsCardVo.getPageSize());
            paramsMap.put("isDetele", 1);
            paramsMap.put("orderByClause", " gmt_create desc ");

            // 门禁卡号
            if (!StringUtil.isEmpty(wmsCardVo.getCardNum())) {
                paramsMap.put("cardNum", wmsCardVo.getCardNum());
            }
            // 借登录账户
            if (!StringUtil.isEmpty(wmsCardVo.getDriverUserName())) {
                paramsMap.put("driverUserName", wmsCardVo.getDriverUserName());
            }
            // 司机姓名
            if (!StringUtil.isEmpty(wmsCardVo.getName())) {
                paramsMap.put("name", wmsCardVo.getName());
            }
            // 状态
            if (wmsCardVo.getStatus() != null) {
                paramsMap.put("status", wmsCardVo.getStatus());
            }
            // 启用开始时间
            if (!StringUtil.isEmpty(wmsCardVo.getStartTime())) {
                paramsMap.put("startTime", wmsCardVo.getStartTime());
            }
            // 启用结束时间
            if (!StringUtil.isEmpty(wmsCardVo.getEndTime())) {
                paramsMap.put("endTime", wmsCardVo.getEndTime());
            }
            // 创建开始时间
            if (!StringUtil.isEmpty(wmsCardVo.getStartCreateTime())) {
                paramsMap.put("startCreateTime", DateUtils.StrToDate(wmsCardVo.getStartCreateTime(), DateUtils.YYYY_MM_DD));
            }
            // 创建结束时间
            if (!StringUtil.isEmpty(wmsCardVo.getEndCreateTime())) {
                Date date = DateUtils.StrToDate(wmsCardVo.getEndCreateTime(), DateUtils.YYYY_MM_DD);
                date.setTime(date.getTime() + 24*3600000 - 1);
                paramsMap.put("endCreateTime", date);
            }

            // 查询借用登记数据
            List<WmsCard> wmsCardList = cardService.selectCardLine(paramsMap);
            // 借用登记数据统计
            Integer count = cardService.countCardLineCount(paramsMap);
            count = count==null?0:count;

            wmsCardVo.setTotalRecord(count);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("totalRecord", wmsCardVo.getTotalRecord());
            map.put("totalPage", wmsCardVo.getTotalPage());
            map.put("pageNo", wmsCardVo.getPageNo());
            map.put("pageSize", wmsCardVo.getPageSize());
            map.put("wmsBorrowCarList", wmsCardList);

            resultDTO = new ResultDTO<Object>(true, map, "成功获取门禁卡列表");
        }catch (BusinessException e) {
            LOGGER.error("CardController.cardLine businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("CardController.cardLine error: {}", e);
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 新增
     *
     * @param wmsCardVo
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultDTO<Object> add(@RequestBody WmsCardVo wmsCardVo, HttpServletRequest request) {
        LOGGER.info("CardController.add param: {}" + wmsCardVo.toString());
        ResultDTO resultDTO = null;

        try {
            String userId = request.getHeader("userId");
            WmsCard wmsCard = new WmsCard();
            BeanUtils.copyProperties(wmsCardVo, wmsCard);
            wmsCard.setCreateBy(userId);
            cardService.add(wmsCard);
            resultDTO = new ResultDTO<Object>(true, "成功添加");
        }catch (BusinessException e) {
            LOGGER.error("CardController.add businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("CardController.add error: {}", e);
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 修改
     *
     * @param wmsCardVo
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    public ResultDTO<Object> modify(@RequestBody WmsCardVo wmsCardVo, HttpServletRequest request) {
        LOGGER.info("CardController.modify param: {}" + wmsCardVo.toString());
        ResultDTO resultDTO = null;

        try {
            if (wmsCardVo.getId() == null) {
                throw new BusinessException("id不能为空!");
            }
            String userId = request.getHeader("userId");
            WmsCard wmsCard = new WmsCard();
            BeanUtils.copyProperties(wmsCardVo, wmsCard);
            wmsCard.setUpdateBy(userId);
            cardService.modify(wmsCard);
            resultDTO = new ResultDTO<Object>(true, "成功编辑");
        }catch (BusinessException e) {
            LOGGER.error("CardController.modify businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("CardController.modify error: {}", e);
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 绑定卡号, 获取当前可用司机
     *
     * @return
     */
    @RequestMapping(value = "/queryDriverUser", method = RequestMethod.GET)
    public ResultDTO<Object> queryDriverUser() {
        LOGGER.info("CardController.queryDriverUser param: {}" );
        ResultDTO resultDTO = null;

        try {
            List<SysUser> sysUsers = cardService.queryDriverUser();
            resultDTO = new ResultDTO<Object>(true, sysUsers, "获取司机成功");
        }catch (BusinessException e) {
            LOGGER.error("CardController.add businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("CardController.add error: {}", e);
            resultDTO = new ResultDTO(false, "获取司机失败");
        }
        return resultDTO;
    }
}
